/** 浏览器环境下专用 */
export default {

    /**
     * 浏览器下 字符串 转  base64 编/解 码
     * https://developer.mozilla.org/zh-CN/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Appendix.3A_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer
     * @param sString
     * @return {string}
     */
    btoaUTF16(sString) {
        let aUTF16CodeUnits = new Uint16Array(sString.length);
        Array.prototype.forEach.call(aUTF16CodeUnits, function (el, idx, arr) {
            arr[idx] = sString.charCodeAt(idx);
        });
        return btoa(String.fromCharCode.apply(null, new Uint8Array(aUTF16CodeUnits.buffer)));
    },

    /**
     *
     * @param sBase64 {string}  base64 string
     * @return {string}
     */
    atobUTF16(sBase64) {
        let sBinaryString = atob(sBase64), aBinaryView = new Uint8Array(sBinaryString.length);
        Array.prototype.forEach.call(aBinaryView, function (el, idx, arr) {
            arr[idx] = sBinaryString.charCodeAt(idx);
        });
        return String.fromCharCode.apply(null, new Uint16Array(aBinaryView.buffer));
    },


    /**
     *
     * 浏览器下  string 转换成 arraybuffer
     *  使用了  TextEncoder 和 TextDecoder
     * Convert String to ArrayBuffer via TextEncoder
     *
     * @see https://developer.mozilla.org/zh-CN/docs/Web/API/TextEncoder
     * @input {string}
     * @return {ArrayBuffer}
     */
    str2ab(input) {
        const view = this._str2Uint8Array(input);
        return view.buffer
    },

    /**
     * 浏览器下  arraybuffer 转换成 string
     * Convert ArrayBuffer/TypedArray to String via TextDecoder
     *
     * @see https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder
     * @return {string}
     */
    ab2str(
        input, //: ArrayBuffer | Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array,
        outputEncoding = 'utf8' // : string = 'utf8',
    ) {
        const decoder = new TextDecoder(outputEncoding);
        return decoder.decode(input)
    },

    /** Convert String to Uint8Array */
    /**
     * @param input {string}
     * @return {Uint8Array}
     */
    _str2Uint8Array(input) {
        const encoder = new TextEncoder();
        const view = encoder.encode(input);
        return view
    },
};

// let str = 'helloworld!我们的队伍向太阳!';
// let arrbuf = browser_utils.str2ab(str);
// console.log(browser_utils.ab2str(arrbuf));

